<template>
  <div class="water-quality-dashboard">

    <el-card shadow="hover" class="mb-6">
            <div slot="header" class="card-header">
        <h3 class="card-title">自动站最新水质状况</h3>
      </div>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="4" v-for="(item, index) in overviewData" :key="index">
          <div class="stat-card">
            <el-statistic :title="item.label" :value="item.value"
              :value-style="{ color: '#409EFF', fontSize: '20px', fontWeight: 'bold' }" :suffix="item.suffix"
              animation-duration="1500">
            </el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 水质类别分布环形图 -->
    <el-card shadow="hover" class="mb-6">
      <!-- <div slot="header">
        <span>水质类别分布</span>
      </div> -->
                <div slot="header" class="card-header">
        <h3 class="card-title">水质类别分布</h3>
      </div>
      <div class="chart-container">
        <div ref="waterTypeChart" class="chart" :style="{ width: '100%', height: '300px' }"></div>
      </div>
    </el-card>

    <!-- 主要污染物及占比柱状图 -->
    <el-card shadow="hover">
      <div slot="header" class="filter-header">
        <!-- 标题单独一行 -->

 
        <h3 class="card-title">主要污染物及占比</h3>

        <!-- 筛选控件放在下一行 -->
        <div class="filter-controls">
          <!-- 按日/按月切换 -->
          <el-radio-group v-model="timeGranularity" size="mini" class="time-granularity"
            @change="handleGranularityChange">
            <el-radio-button label="day">按日</el-radio-button>
            <el-radio-button label="month">按月</el-radio-button>
          </el-radio-group>

          <el-date-picker v-model="dateRange" :type="daterangeType" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="mini" :format="timeGranularity === 'day' ? 'yyyy-MM-dd' : 'yyyy-MM'"
            :value-format="timeGranularity === 'day' ? 'yyyy-MM-dd' : 'yyyy-MM'" :picker-options="datePickerOptions"
            @change="handleDateChange" class="date-picker"></el-date-picker>
        </div>
      </div>
      <div class="zywrw-container">
        <!-- 超标日期前三 -->
        <div class="data-item">
          <li class="zywrw-title">超标日期前三：</li>
          <span class="zywrw-data-string">
            {{ cbThreeDay }}
          </span>
        </div>
        <!-- 因子累计前三 -->
        <div class="data-item">
          <li class="zywrw-title">因子累计前三：</li>
          <span class="zywrw-data-string">
            {{ cbThreeItem }}
          </span>
        </div>
      </div>

      <div class="chart-container pollutant-chart-container">
        <div ref="pollutantChart" class="chart" :style="{ width: '100%', height: '400px' }"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAutoWaterQuality, getDayPollutantsPropor, getMonthPollutantsPropor } from "../../api/water.js";
import * as echarts from 'echarts'

const waterColors = {
  'Ⅰ类': 'rgb(204, 255, 255)', // 优 #ccffff
  'Ⅱ类': 'rgb(0, 204, 255)',   // 良好 #00ccff
  'Ⅲ类': 'rgb(0, 255, 0)',     // 轻度污染 #00ff00
  'Ⅳ类': 'rgb(255, 255, 0)',   // 中度污染 #ffff00
  'Ⅴ类': 'rgb(255, 155, 0)',   // 重度污染 #ff9b00
  '劣Ⅴ类': 'rgb(255, 0, 0)',   // 严重污染 #ff0000
  '无类别': 'rgb(128, 128, 128)',
}


// 常量配置
const CONSTANTS = {
  // 图表相关样式配置
  CHART_STYLES: {
    TOOLTIP: {
      BACKGROUND: 'rgba(255, 255, 255, 0.9)',
      BORDER_COLOR: '#ddd',
      BORDER_WIDTH: 1,
      TEXT_COLOR: '#333'
    },
    AXIS: {
      LINE_COLOR: '#ccc',
      LABEL_COLOR: '#606266',
      SPLIT_LINE_COLOR: '#f0f0f0'
    },
    LEGEND: {
      TEXT_COLOR: '#606266'
    }
  },
  // 默认日期范围
  DEFAULT_DATE_RANGES: {
    DAY: (function () {
      const today = new Date();
      const oneWeekAgo = new Date(today);
      oneWeekAgo.setDate(today.getDate() - 7);

      const formatDate = (date) => {
        return date.getFullYear() + '-' +
          String(date.getMonth() + 1).padStart(2, '0') + '-' +
          String(date.getDate()).padStart(2, '0');
      };

      return [formatDate(oneWeekAgo), formatDate(today)];
    })(),
    MONTH: (function () {
      const today = new Date();
      const oneYearAgo = new Date(today);
      oneYearAgo.setFullYear(today.getFullYear() - 1);

      const formatMonth = (date) => {
        return date.getFullYear() + '-' +
          String(date.getMonth() + 1).padStart(2, '0');
      };

      return [formatMonth(oneYearAgo), formatMonth(today)];
    })()
  }
}
export default {
  name: 'WaterQualityDashboard',
  data() {
    return {
      // 时间粒度：day-按日，month-按月
      timeGranularity: 'day',
      // 日期范围
      dateRange: CONSTANTS.DEFAULT_DATE_RANGES.DAY,
      daterangeType: "daterange",

      currentPollutantData: null,
      // 图表实例
      waterTypeChart: null,
      pollutantChart: null,
      // 日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用未来日期
          return time.getTime() > Date.now();
        }
      },
      startTime: '',
      endTime: '',
      cbThreeDay: '',
      cbThreeItem: '',
      overview: {
        isAutoSegmentsize: 56,        // 自动站总数
        offlinesize: 20,               // 无数据
        isOvesize: 7,              // 超标
        compliancerate: 80.6,  // 达标率
        excellentsize: 19,          // 优良数
        excellent: '52.8'  // 优良率
      },
      overviewData: [],
      waterTypeData: [],
      pollutantData: {
        dates: [],
        pollutants: [
        ]
      },
      // 水质数据
      waterQualityData: {


      }
    }
  },
  computed: {

  },
  watch: {

    /**
     * 监听时间粒度变化，更新日期范围和图表
     */
    timeGranularity(newVal) {
      this.dateRange = newVal === 'month'
        ? CONSTANTS.DEFAULT_DATE_RANGES.MONTH
        : CONSTANTS.DEFAULT_DATE_RANGES.DAY
    }
  },
  mounted() {
    this.getAutoWaterQualityData()
    this.getMonitoringData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 清理事件监听和图表实例，防止内存泄漏
    window.removeEventListener('resize', this.handleResize)
    this.waterTypeChart?.dispose()
    this.pollutantChart?.dispose()
  },
  methods: {

    formatDate(date) {
      if (!date) return '';
      if (date instanceof Date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      return date;

    },
    formatMonth(date) {
      if (!date) return '';
      if (date instanceof Date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      }
      return date;
    },
    /**
  * 当前时间粒度下的污染物数据
  */
    setCurrentPollutantData() {

      this.currentPollutantData = this.pollutantData

    },
    /**
     * 概览数据格式化
     * 将原始数据转换为统计卡片所需的格式
     */
    getAutoWaterQualityData() {
      getAutoWaterQuality().then(res => {
        let data = res.data;
        this.overview = res.data[0];
        this.overviewData = [
          {
            label: '自动站',
            value: Number(this.overview.isAutoSegmentsize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',

          },
          {
            label: '无数据',
            value: Number(this.overview.offlinesize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',

          },
          {
            label: '超标',
            value: Number(this.overview.isOvesize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',


          },
          {
            label: '达标率',
            value: Number(this.overview.compliancerate),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '%'
          },
          {
            label: '优良数',
            value: Number(this.overview.excellentsize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',


          },
          {
            label: '优良率',
            value: Number(this.overview.excellent),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '%'
          }
        ];
        data.forEach(element => {
          //console.log(element);
          this.waterTypeData.push({ value: element.size, name: element.type, itemStyle: { color: waterColors[element.type] } })

        });
        this.initWaterTypeChart()

      })
    },


    getMonitoringData() {
      let apiFunction;
      let startTime;
      let endTime;

      if (this.timeGranularity === 'day') {
        apiFunction = getDayPollutantsPropor;
        startTime = this.formatDate(this.dateRange[0]);
        endTime = this.formatDate(this.dateRange[1]);
      } else if (this.timeGranularity === 'month') {
        apiFunction = getMonthPollutantsPropor;
        startTime = this.formatMonth(this.dateRange[0]);
        endTime = this.formatMonth(this.dateRange[1]);
      } else {
        console.warn('未知的时间段类型:', this.timePeriod);
        return;
      }

      apiFunction({
        id: this.featureId,
        startTime: startTime,
        endTime: endTime
      }).then(res => {
        let data = res.data;
        if (this.timeGranularity === 'day') {
          this.cbThreeDay = data.cbThreeDay.map(item => `${item.DATATIME}(${item.DATACOUNT})`).join(',');;
        }
        if (this.timeGranularity === 'month') {
          this.cbThreeMonth = data.cbThreeMonth.map(item => `${item.ITEMNAME}(${item.DATACOUNT})`).join(',');;
        }

        this.cbThreeItem = data.cbThreeItem.map(item => `${item.ITEMNAME}(${item.DATACOUNT})`).join(',');;

        this.pollutantData.dates = data.dayList;
        let itemNameList = data.itemNameList;
        let dataList = data.dataList;
        let pollutants = [];
        itemNameList.forEach((item, index) => {
          pollutants.push({ "name": item, "data": dataList[index] })
        });
        this.pollutantData.pollutants = pollutants;
        this.setCurrentPollutantData()
        this.initPollutantChart()
      }).catch(error => {
        console.error('获取监测数据失败:', error);
      });
    },
    getDayPollutantsProporData(startTime, endTime) {

      let query = {
        startTime: startTime,
        endTime: endTime
      }
      getDayPollutantsPropor(query).then(res => {
        let data = res.data;
        this.cbThreeDay = data.cbThreeDay.map(item => `${item.DATATIME}(${item.DATACOUNT})`).join(',');;
        this.cbThreeItem = data.cbThreeItem.map(item => `${item.ITEMNAME}(${item.DATACOUNT})`).join(',');;

        this.pollutantData.dates = data.dayList;
        let itemNameList = data.itemNameList;
        let dataList = data.dataList;
        let pollutants = [];
        itemNameList.forEach((item, index) => {
          pollutants.push({ "name": item, "data": dataList[index] })
        });
        this.pollutantData.pollutants = pollutants;
        this.setCurrentPollutantData()
        this.initPollutantChart()
      })
    },

    /**
     * 初始化图表
     */
    initWaterTypeChart() {
      // 初始化水质类别图表
      if (this.$refs.waterTypeChart) {
        this.waterTypeChart = echarts.init(this.$refs.waterTypeChart)
        this.waterTypeChart.setOption(this.getWaterTypeOption())
      }


    },
    initPollutantChart() {
      // 初始化污染物图表
      if (this.pollutantChart) {
        this.pollutantChart.setOption(this.getPollutantOption())
      }
      else {
        if (this.$refs.pollutantChart) {
          this.pollutantChart = echarts.init(this.$refs.pollutantChart)
          this.pollutantChart.setOption(this.getPollutantOption())
        }
      }

    },


    /**
     * 获取水质类别图表配置
     */
    getWaterTypeOption() {
      const { TOOLTIP, LEGEND } = CONSTANTS.CHART_STYLES

      return {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
          backgroundColor: TOOLTIP.BACKGROUND,
          borderColor: TOOLTIP.BORDER_COLOR,
          borderWidth: TOOLTIP.BORDER_WIDTH,
          textStyle: { color: TOOLTIP.TEXT_COLOR }
        },
        legend: {
          orient: 'vertical',
          right: '15%',
          top: 'center',
          data: this.waterTypeData.map(item => item.name),
          textStyle: { color: LEGEND.TEXT_COLOR },
          itemGap: 12,
          formatter: (name) => {
            const item = this.waterTypeData.find(data => data.name === name);
            return `${name} ${item ? item.value : 0}个`;
          }
        },
        series: [
          {
            name: '水质类别',
            type: 'pie',
            center: ['35%', '50%'],
            radius: ['40%', '70%'],
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: { show: false },
            emphasis: {
              label: { show: true, fontSize: 16, fontWeight: 'bold', position: 'center' }
            },
            labelLine: { show: false },
            data: this.waterTypeData
          }
        ]
      }
    },

    /**
     * 获取污染物图表配置
     */
    getPollutantOption() {

      const { TOOLTIP, AXIS } = CONSTANTS.CHART_STYLES
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: TOOLTIP.BACKGROUND,
          borderColor: TOOLTIP.BORDER_COLOR,
          borderWidth: TOOLTIP.BORDER_WIDTH
        },
        legend: {
          data: this.currentPollutantData.pollutants.map(item => item.name),
          // top: 0,
          // left: 'center',
          // width: '100%',
          // textAlign: 'center',
          type: 'scroll',
          top: 0,
          left: 'center',
          right: 'center',
          width: '90%',
          textAlign: 'center',
          itemWidth: 15,
          itemHeight: 10,
          textStyle: { fontSize: 12 }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: this.currentPollutantData.dates,
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR },
          splitLine: { lineStyle: { color: AXIS.SPLIT_LINE_COLOR } }
        },
        series: this.currentPollutantData.pollutants.map(pollutant => ({
          name: pollutant.name,
          type: 'bar',
          stack: '总量', // 添加堆叠配置
          data: pollutant.data,
          itemStyle: { color: pollutant.color },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.3)' }
          },
          barCategoryGap: '30%'
        }))
        // series: this.currentPollutantData.pollutants.map(pollutant => ({
        //   name: pollutant.name,
        //   type: 'bar',
        //   data: pollutant.data,
        //   itemStyle: { color: pollutant.color },
        //   emphasis: {
        //     itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.3)' }
        //   },
        //   barCategoryGap: '30%'
        // }))
      }
    },

    /**
     * 处理窗口大小变化，调整图表尺寸
     */
    handleResize() {
      this.waterTypeChart?.resize()
      this.pollutantChart?.resize()
    },

    /**
     * 处理时间粒度变化
     */
    handleGranularityChange(granularity) {
      if (granularity == 'day') { this.daterangeType = "daterange" }
      else { this.daterangeType = "monthrange" }


      this.timeGranularity = granularity
      this.getMonitoringData()
    },

    /**
     * 处理日期范围变化
     */
    handleDateChange(range) {

      this.getMonitoringData();


    }
  }
}

</script>

<style scoped>
.water-quality-dashboard {
  background-color: #f5f7fa;
  max-height: 100vh;
  padding: 5px;
}
.card-header {
display: flex;
align-items: center;
}

.card-title {
font-size: 18px;
font-weight: bold;
color: #333;
}
.el-card__header {
  padding: 5px !important;
}
.stat-card {
  background-color: #fff;
  padding: 5px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
  border-color: transparent;
}

.el-statistic__title {
  color: #606266 !important;
  margin-bottom: 8px !important;
  font-size: 14px !important;
  font-weight: normal !important;
}

.el-statistic__prefix {
  margin-right: 8px !important;
  font-size: 18px !important;
}

/* 调整头部样式 */
.filter-header {
  margin-top: 4px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 4px;
}




.time-granularity {
  margin-right: 0;
}

.zywrw-title {
  display: inline-block;
  margin-right: 10px;
  white-space: nowrap;
}

.data-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.data-item .zywrw-data-string {
  flex: 1;
}

.zywrw-data-string {
  padding: 2px 4px;
  font-weight: bold;
  color: #409EFF;
}

.pollutant-chart-container {
  padding-top: 20px;
}

/* .date-picker {
  width: auto;
} */

.chart-container {
  position: relative;
}

/* 响应式样式调整 */
@media (max-width: 768px) {
  .chart {
    height: 300px !important;
  }

  .el-col-xs-12 {
    width: 50% !important;
  }

  .filter-controls {
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }

  .time-granularity,
  .date-picker {
    width: 100%;
  }

  .pollutant-chart-container {
    padding-top: 15px;
  }
}
</style>
